/*
通讯录

2021-10-04
*/

package ding

import (
	"encoding/json"
	"fjj/tool/dbOperate"
	universal "fjj/tool/universal"
	"fmt"
	"strconv"
	"strings"
)

// 获取企业员工人数
func getEmployeeCount(ack *string) int {

	url := fmt.Sprintf("https://oapi.dingtalk.com/user/get_org_user_count?access_token=%s&onlyActive=0", *ack)

	g := universal.Get(&url)
	println("获取企业员工人数 BODY：", g)

	e := employee_count_back{}
	err := json.Unmarshal([]byte(g), &e)
	if err != nil {
		fmt.Println("EmployeeCount JSON Umarshal failed:", err)
		return 0
	}

	return e.Count
}

// 网页请求获取在职人员ID列表，分页，一次最多50个
// 返回数组字符串和下一次分页调用的offset值
func getemployeeIdList(ack *string, offset *int) ([]string, int) {

	url := fmt.Sprintf("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob?access_token=%s", *ack)
	data := []byte(fmt.Sprintf("{'status_list':'2,3,5,-1','size':'50','offset':'%d'}", *offset))
	sentType := "application/json;charset=utf-8"
	p, _ := universal.Post(&url, &sentType, data)

	println("查询企业在职员工userid列表 BODY:", p)

	e := employe_id_list_back{}
	err := json.Unmarshal([]byte(p), &e)
	if err != nil {
		fmt.Println("temployeeIdList JSON Umarshal failed:", err)
		return []string{""}, 0
	}

	return e.Result.DataList, e.Result.NextCursor
}

// 获取所有在职人员ID列表
func GetAllEmployeeIdList(ack *string) []string {

	offset := 0
	iTemp := -1
	strList := make([]string, 0)

	for iTemp != 0 {
		l, o := getemployeeIdList(ack, &offset)
		offset = o
		iTemp = o
		for _, value := range l {
			//println(key, ":", value)
			strList = append(strList, value)
		}
	}

	return strList
}

/*
取所有部门
ID-带上级的部门名
*/
func getDepartmentInfo(ack *string) map[int]string {
	url := fmt.Sprintf("https://oapi.dingtalk.com/department/list?access_token=%s&lang=zh_CN&fetch_child=true&id=1", *ack)

	g := universal.Get(&url)
	println("部门列表 BODY：", g)

	d := department_back{}
	err := json.Unmarshal([]byte(g), &d)
	if err != nil {
		fmt.Println("EmployeeCount JSON Umarshal failed:", err)
		return nil
	}

	//取返回的部门IP，部门名
	type mapTemp struct {
		name     string
		parentId int
	}
	mapS := make(map[int]*mapTemp)
	l := len(d.Department)
	//fmt.Println(l)

	for i := 0; i < l; i++ {
		st := mapTemp{d.Department[i].Name, d.Department[i].Parentid}
		mapS[d.Department[i].ID] = &st
	}

	//fmt.Printf("%v\n",mapS)

	//把与上级部门组合新部门名
	mapS2 := make(map[int]string)
	for i := 0; i < l; i++ {
		name2 := d.Department[i].Name
		pId := d.Department[i].Parentid
		for {
			if pId == 1 {
				break
			}
			name2 = mapS[pId].name + "-" + name2
			pId = mapS[pId].parentId
		}
		mapS2[d.Department[i].ID] = name2
	}

	//fmt.Printf("%v\n", mapS2)
	return mapS2
}

// 取花名册信息
func getEmployeeInfo(ack *string, employeeId []string) []dbOperate.EmployeeInfo {

	url := fmt.Sprintf("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/v2/list?access_token=%s", *ack)
	sentType := "application/json;charset=utf-8"
	getTab := "sys00-name,sys00-mainDeptId,sys00-deptIds,sys01-employeeStatus"

	//ID列表分组
	idList := []string{}
	iCount := len(employeeId)
	//100个ID为一组
	for iCount > 0 {
		str := ""
		div := iCount / 100
		mov := iCount % 100

		if mov > 0 {
			j := div * 100
			for i := div*100 + mov; i > j; i-- {
				str = employeeId[i-1] + "," + str
			}
			iCount -= mov
		} else {
			j := (div - 1) * 100
			for i := div * 100; i > j; i-- {
				str = employeeId[i-1] + "," + str
			}
			iCount -= 100
		}

		//删除最后一个逗号
		str = strings.TrimRight(str, ",")
		//加入数组
		idList = append(idList, str)
	}

	//fmt.Println(len(idList))
	//fmt.Printf("%v\n",idList)

	employeeList := []dbOperate.EmployeeInfo{}

	for iCount = len(idList); iCount > 0; iCount-- {
		data := []byte(fmt.Sprintf("{'agentid':'%s','field_filter_list':'%s','userid_list':'%s'}",
			cfg.Ding.AgentId, getTab, idList[iCount-1]))
		p, _ := universal.Post(&url, &sentType, data)

		//println("查询企业在职员工花名册 BODY:", p)

		//转结构体
		e := employee_hrm_back{}
		err := json.Unmarshal([]byte(p), &e)
		if err != nil {
			fmt.Println("temployeeIdList JSON Umarshal failed:", err)
			return nil
		}

		//取目标数据
		for i := len(e.Result); i > 0; i-- {
			employeeInfo := getEmployeeInfo2(e.Result[i-1])
			employeeList = append(employeeList, employeeInfo)
		}

	}

	return employeeList
}

func getEmployeeInfo2(r employee_result) dbOperate.EmployeeInfo {
	var dn, dId, deId, deptId, status string

	dId = r.Userid

	for i := len(r.FieldDataList); i > 0; i-- {
		t := r.FieldDataList[i-1].FieldCode
		switch t {
		case "sys00-name":
			dn = r.FieldDataList[i-1].FieldValueList[0].Value
		case "sys00-mainDeptId":
			deId = r.FieldDataList[i-1].FieldValueList[0].Value
		case "sys00-deptIds":
			deptId = r.FieldDataList[i-1].FieldValueList[0].Value
		default:
			status = r.FieldDataList[i-1].FieldValueList[0].Value
		}
	}
	st, _ := strconv.Atoi(status)
	return dbOperate.EmployeeInfo{Name: dn, DingID: dId, PrimarydepartmentID: deId, DepartmentListID: deptId, Status: st}

}
